using Microsoft.AspNetCore.Mvc;
using MvcSoft1Demo.Models;
using System.Linq;
using MvcSoft1Demo.Repository;
using MvcSoft1Demo.RequestParams;

namespace MvcSoft1Demo.Controllers
{
    public class StudentController : Controller
    {
        public IActionResult Index()
        {
            var schoolRep = new EfRepository<School>();
            var school = schoolRep.Table.FirstOrDefault();
            if (school == null)
            {
                schoolRep.Insert(new School
                {
                    SchoolName = "闽大"
                });
            }
            var studentRep = new EfRepository<Student>();
            var students = studentRep.Table.Where(x => x.IsDeleted == false).ToList();
            return View(students);
        }

        public IActionResult CreateOrEdit()
        {
            return View();
        }

        public IActionResult Save(StudentParam request)
        {
            var studentRep = new EfRepository<Student>();
            if (request.Id > 0)
            {

            }
            else
            {
                studentRep.Insert(
                    new Student
                    {
                        StudentName = request.Name.Trim(),
                        Remarks = request.Remarks.Trim(),
                        SchoolId = 1
                    }
                );
            }
            return Ok();
        }

        public IActionResult Query(QueryParam request)
        {
            var studentRep = new EfRepository<Student>();
            var keyword = request.Keyword != null ? request.Keyword.Trim() : "";
            var students = studentRep.Table.Where(x => x.IsDeleted == false);

            if (keyword.Length > 0)
            {
                students=students.Where(x=>x.StudentName.Contains(keyword));
            }
            return Json(students.ToList());
        }
    }
}